package com.gmail.bloim.serg.testrunner;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

/**
 * User: Администратор
 * Date: 25.04.13
 * Time: 11:40
 */
public class TestScanner {
    private final File dir;
    private final Properties props;

    public TestScanner(File dir, Properties testDefaults) {
        this.dir = dir;
        props = new Properties(testDefaults);
        try {
            props.load(new FileInputStream(new File(dir, "test.properties")));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Set<Test> scanTests() {
        File[] files = null;
        try {
            files = dir.listFiles();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (files == null)
            return new HashSet<Test>();
//        Arrays.sort(files, new Comparator<File>() {
//            @Override
//            public int compare(File o1, File o2) {
//                return o1.getName().compareTo(o2.getName());
//            }
//        });
        Set<Test> tasks = new TreeSet<Test>(new Comparator < Test >(){
            @Override
            public int compare(Test o1, Test o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        Map<String, File> stdIns = new HashMap<String, File>();
        Map<String, File> stdOuts = new HashMap<String, File>();
        Map<String, File> args = new HashMap<String, File>();
        Set<String> names = new HashSet<String>();
        for (File file : files) {
            String fullName = file.getName();
            String baseName = FilenameUtils.getBaseName(fullName);
            String extension = FilenameUtils.getExtension(fullName);
            if ("in".equals(extension)) {
                stdIns.put(baseName, file);
                names.add(baseName);
            }
            if ("out".equals(extension)) {
                stdOuts.put(baseName, file);
                names.add(baseName);
            }
            if ("arg".equals(extension)) {
                args.put(baseName, file);
                names.add(baseName);
            }
        }
        for (String name : names) {
            Test t = new Test(stdIns.get(name), stdOuts.get(name), args.get(name));
            tasks.add(t);
        }
        return tasks;
    }

    public String getMainClass() {
        return props.getProperty("program.mainclass");
    }
}
